package com.example.hospitalsystem.utils;

import jakarta.mail.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import jakarta.mail.internet.MimeMessage;

import java.util.concurrent.ThreadLocalRandom;


@Component
public class MailUtils {

    @Value("${spring.mail.username}")
    private String mailSender;

    @Autowired
    private JavaMailSender javaMailSender;

    /*发送验证信息的邮件*/
    public void sendMail(String to,String text,String title){
        try{
            //解决本DNS未配置，ip->域名场景下，邮件发送太慢的问题
            System.getProperties().setProperty("mail.mime.address.usecanonicalhostname","false");
            MimeMessage mailMessage=javaMailSender.createMimeMessage();

            //使用MimeMessage设置属性和内容
            MimeMessageHelper helper=new MimeMessageHelper(mailMessage,true);
            //获取邮件的会话对象Session
            Session session=mailMessage.getSession();
            //设置日志打印控制器 会在控制台输出邮件发送的详细日志信息
            session.setDebug(true);

            //解决本地DNS配置 ip->域名场景下，邮件发送太慢的问题
            session.getProperties().setProperty("mail.smtp.localhost","myComputer");

            //设置邮件的发件人地址
            helper.setFrom(mailSender);

            //设置邮件的收件人地址 主题和内容
            helper.setTo(to);
            helper.setSubject(title);
            helper.setText(text,false);
            //使用注入的javaMailSender对象发送邮件
            javaMailSender.send(mailMessage);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
    //用于生成一个六位数的随机验证码
    public String getCode(){
        return String.valueOf(ThreadLocalRandom.current().nextInt(100000,1000000));
    }
}
